<template>
  <div class="app-container">
    <div class="publicgoods-details-container">
      <div class="product">
        <div class="proLeft">
          <!-- 主图 -->
          <div class="img_box" ref="imRef" @mousemove="move" @mouseover="flag = true" @mouseout="flag = false">
            <img class="img-yuan" :src="showMyImg ? skuImage : form.imageURLs[hoveIndex]"/>
            <!-- 右侧大图 -->
            <div class="big_img_box" v-show="flag">
              <img :src="showMyImg ? skuImage : form.imageURLs[hoveIndex]"
                   :style="{ left: left + 'px', top: top + 'px' }" alt/>
            </div>
            <div class="mark" :style="{ left: l + 'px', top: t + 'px' }" v-show="flag">
              <el-image :style="{ left: -l + 'px', top: -t + 'px' }"
                        :src="showMyImg ? skuImage : form.imageURLs[hoveIndex]"
                        :preview-src-list="imageURLList"></el-image>
            </div>
          </div>
          <!-- 轮播 -->
          <div class="spec">
            <div class="specLeft" @click="moveLeft">
              <i class="el-icon-arrow-left"></i>
            </div>
            <div class="specCount">
              <div class="specUl" :style="{width: form.imageURLs.length * 75 + 'px',  left: -carouselLeft + 'px'}">
                <div class="specImg-wrapper" :class="{ ulImgActive: index == hoveIndex }"
                     v-for="(item, index) in form.imageURLs" :key="item + index" @click="clickStyle(index)">
                  <img class="specImg" :src="item" alt=""/>
                </div>
              </div>
            </div>
            <div class="specRight" @click="moveRight"><i class="el-icon-arrow-right"></i></div>
          </div>
        </div>
        <!-- 信息 -->
        <div class="proCenter" v-if="!isTask">
          <div class="proCenterTop">{{ form.subject }}</div>
          <div class="proCenterCenter">
            <div class="product-pice font14">
              <span>销售价格</span>
              <span class="pice" v-if="isGather">{{ newSkuDetail.skuPrice || '-' }}</span>
              <span class="pice" v-else>{{ usPrice || '-' }}</span>
              <span style="margin-left: 20px;">skuCode</span>
              <span class="pice">{{ newSkuDetail.skuCode || '-' }}</span>
            </div>
          </div>
          <!-- 规格 -->
          <div class="selectBox">
            <div v-if="form.expand" class="tagBox font14">
              <div v-for="item in form.expand.skuProperty" :key="item.value" :class="['tagBox-item',]">
                <div class="tagBox-item-name">{{ item.name }}：</div>
                <div class="tagBox-item-list" v-if="item.list.length > 0">
                  <div v-for="tag in item.list" :key="'tag' + tag.value" @click="activeTag(item, tag)"
                       :class="['tag-wrapper', activeTagIndex.filter((items) => { return items.name == item.value && items.value == tag.value }).length > 0 ? 'activeTag' : '']">
                    {{ tag.name }}
                  </div>
                </div>
              </div>
            </div>
          </div>
          <!-- sku价格 -->
          <div class="skupriceBox" v-if="freightMap.length > 0">
            <el-table :data="[{}]" border :header-cell-style="{'text-align':'center'}"
                      :cell-style="{'text-align':'center'}" header-cell-class-name="table-header" width="100%"
                      current-row-key="uid" row-class-name="table-row" empty-text>
              <el-table-column v-for="(leftTitle) in freightMap" :key="leftTitle.shiptoCountry"
                               :label="leftTitle.shiptoCountry" width="90">
                <template><span>{{ leftTitle.price }}</span></template>
              </el-table-column>
            </el-table>
          </div>
        </div>
      </div>

      <!-- 详情 -->
      <div class="content-wrapper">
        <div class="content-title-wrapper clearfix">
          <div v-for="(item, index) in tabList" :key="index" class="content-title"
               :class="{'active': tabIndex == item.value}" @click="tabIndex = item.value">
            {{ item.name }}
          </div>
        </div>
        <div v-if="tabIndex == '0'" class="content">
          <div class="detail-content">{{ form.detail }}</div>
          <div class="detail-img">
            <div v-for="(item, index) in form.imageURLs" :key="'detail' + index" class="ulImg">
              <img :src="(item.indexOf('http://') === -1 && item.indexOf('https://') === -1) ? domain + item : item"/>
            </div>
          </div>
        </div>
        <div v-if="tabIndex == '1'" class="content">
          <div class="detail-content">
            <el-form>
              <div class="displayBox">
                <el-form-item v-for="(item, index) in form.customAttributes" :key="index" class="flexbox"
                              :label="item.zhName" label-width="240px">
                  <div class="box-input-item-class">
                    <el-input v-if="item.attributeShowTypeValue == 'input'" v-model.trim="item.attr_value" disabled/>
                    <el-select v-if="item.attributeShowTypeValue == 'list_box'" placeholder=""
                               v-model="item.attr_value_id" disabled>
                      <el-option v-for="(dict, i) in item.values" :key="i" :label="dict.zhName"
                                 :value="dict.attr_value_id"/>
                    </el-select>
                    <el-select v-if="item.attributeShowTypeValue == 'check_box'" placeholder="" multiple
                               v-model="item.attr_value_id" disabled>
                      <el-option v-for="(dict, j) in item.values" :key="j" :label="dict.zhName"
                                 :value="dict.attr_value_id"/>
                    </el-select>
                  </div>
                </el-form-item>
              </div>
            </el-form>
          </div>
        </div>
      </div>
      <div class="shadeBox" v-show="visible" @click="onHide"></div>
    </div>

    <el-backtop></el-backtop>
  </div>
</template>

<script>
import {mapGetters} from 'vuex'
import {getCollectProduct, categoryInfo} from "@/api/attribute";

export default {
  name: "productDetail",
  components: {},
  data() {
    return {
      flag: false,
      // 遮罩层坐标
      l: 0,
      t: 0,
      left: 0, //左移位置
      top: 0, //下移位置
      isShow: false,
      form: {
        imageURLs: []
      },
      visible: false, //选配置的浮层
      hoveIndex: 0, //鼠标滑过图片缩略图的index
      carouselLeft: 0,
      //form.imageURLs轮播图的数据
      // 控制商品规格
      specificationsShow: false,
      newSkuDetail: {}, //选中sku详情信息
      activeTagIndex: [],//选中sku的id
      skuImage: '',  //选中的主图
      showMyImg: false, //是否展示选中的主图
      imageURLList: [],
      tabList: [
        {
          name: '商品详情',
          value: '0'
        },
        {
          name: '商品属性',
          value: '1'
        }
      ],
      tabIndex: '0',
      activeData: '',
      freightMap: [],
      isGather: true, // 是否是采集列表进入的详情页
      usPrice: '', // 美国价格
      isTask: false,//是否从优化任务页面跳转
    };
  },
  computed: {
    ...mapGetters([
      'domain'
    ]),
    property() {
      // const property = [this.form.packageLength, this.form.packageWidth, this.form.packageHeight]
      const property = [this.newSkuDetail.skuLength, this.newSkuDetail.skuWidth, this.newSkuDetail.skuHeight]
      const newProperty = property.filter(item => !!item)
      return newProperty.join('*')
    }
  },
  created() {
    console.log('this.$route.query',this.$route.query)
    if (this.$route.query.v2) {
      this.$route.query.v2 == '0' ? this.isGather = false : this.isGather = true
    }
    if (this.$route.query.v1) {
      this.getInfo(this.$route.query.v1);
    }
    if (this.$route.query.isTask) {
      this.isTask = this.$route.query.isTask
    }
  },
  methods: {
    move(e) {
      // 鼠标相对于网页左上角的坐标
      var x = e.pageX - 130;
      var y = e.pageY - 130;
      // 大图相对于网页左上角的坐标
      var ot = null;
      var ol = null;
      if (this.$refs.imRef) ot = this.$refs.imRef.offsetTop;
      if (this.$refs.imRef) ol = this.$refs.imRef.offsetLeft;
      // 计算鼠标相对于大图左上角的坐标
      x -= ol;
      y -= ot;
      // 限制鼠标相对于大图的坐标变化范围
      x = x < 130 ? 130 : x;
      x = x > 320 ? 320 : x;
      y = y < 130 ? 130 : y;
      y = y > 320 ? 320 : y;
      // 在这个范围内,让遮罩层跟随鼠标移动
      this.l = x - 130;
      this.t = y - 130;
      // 计算放大镜图片坐标
      // 左侧图片移动范围 224 - 130 = 94
      // 右侧大图移动范围 760 - 448 = 312
      // 得出: 右侧大图和左侧小图移动的坐标比例关系  312 / 94 = 3.3
      // this.left = -(x - 130) * 2;
      // this.top = -(y - 130) * 2
      this.left = -(x - 130) * 1.7;
      this.top = -(y - 130) * 1.7;
    },
    // 选择
    activeTag(item, tag) {
      let activeTagList = [];
      let activeList = JSON.parse(JSON.stringify(this.activeTagIndex));
      activeList.forEach((activeTagItem, index) => {
        if (activeTagItem.name == item.value) {
          activeList[index].value = tag.value;
        }
        activeTagList.push(activeTagItem.name + ':' + activeTagItem.value);
      })
      this.activeTagIndex = activeList;
      this.activeData = activeTagList.join(';');
      // 查找sku数据
      this.form.skuList.forEach((skuItem, index) => {
        const activeId = skuItem.skuPropertyIds.indexOf(activeTagList.join(';'));
        if (activeId != -1) {
          return this.newSkuDetail = skuItem
        }
      })
      if (this.form.expand) {
        const oldFreightMap = this.isGather ? JSON.parse(this.form.expand.freightMap || '[]') : JSON.parse(this.form.expand.absoluteQuoteMap || '[]');
        const oldSkuPropertyIds = activeTagList.join(';');
        oldFreightMap.forEach(item => {
          for (let key in item.absoluteQuoteMap) {
            if (oldSkuPropertyIds != key) {
              delete item.absoluteQuoteMap[key]
            } else {
              item.price = item.absoluteQuoteMap[key]
            }
          }
        })
        this.freightMap = oldFreightMap
        if (oldFreightMap.length > 0) this.usPrice = oldFreightMap[0].price
        else this.usPrice = null
      }
      if (this.newSkuDetail.skuImage) {
        this.skuImage = (this.newSkuDetail.skuImage.indexOf('http://') === -1 && this.newSkuDetail.skuImage.indexOf('https://') === -1) ? this.$store.getters.domain + this.newSkuDetail.skuImage : this.newSkuDetail.skuImage
      }
      this.showMyImg = true
      // 放大轮播图
      this.imageURLList = JSON.parse(JSON.stringify(this.form.imageURLs))
      this.imageURLList.unshift(this.skuImage)
    },
    /** 查询产品详情 */
    getInfo(id) {
      this.loading = true;
      getCollectProduct(id).then(res => {
        this.form = res.data
        const categoryId = res.data.categoryId
        if (categoryId) {
          this.getCategoryInfo(categoryId);
        }
        const arr = (res.data.imageURLs || '').split(';').filter(item => !!item)
        const newArr = []
        arr.forEach(item => {
          if (item.indexOf('http://') === -1 && item.indexOf('https://') === -1) {
            newArr.push(this.$store.getters.domain + item)
          } else {
            newArr.push(item)
          }
        })
        this.form.imageURLs = newArr
        this.imageURLList = []
        this.imageURLList = this.form.imageURLs
        // 初始数据
        if (res.data.expand) {
          if (res.data.skuList.length > 0) this.newSkuDetail = res.data.skuList[0];
          this.form.expand.skuProperty = JSON.parse(this.form.expand.skuProperty || '[]');
          this.form.expand.skuProperty.forEach((item, index) => {
            this.activeTagIndex.push({
              name: item.value,
              value: item.list[0].value
            })
          })
          const oldFreightMap = this.isGather ? JSON.parse(this.form.expand.freightMap || '[]') : JSON.parse(this.form.expand.absoluteQuoteMap || '[]');
          const oldSkuPropertyIds = this.form.skuList[0].skuPropertyIds;
          oldFreightMap.forEach(item => {
            for (let key in item.absoluteQuoteMap) {
              if (oldSkuPropertyIds != key) {
                delete item.absoluteQuoteMap[key]
              } else {
                item.price = item.absoluteQuoteMap[key]
              }
            }
          })
          this.freightMap = oldFreightMap
          this.usPrice = oldFreightMap[0].price
        }
        this.loading = false;
      });
    },
    // 获取商品属性
    getCategoryInfo(id) {
      categoryInfo(id).then(res => {
        var resMap = new Map();
        res.data.forEach(item => {
          var attribute = {
            'attr_name_id': item.attr_name_id,
            'attr_name': item.attr_name,
            'zhName': item.zhName || item.attr_name,
            'attr_value_id': item.attr_value_id,
            'attr_value': item.attr_value,
            'values': item.values,
            'attributeShowTypeValue': item.attributeShowTypeValue,
            'required': item.required
          };
          resMap.set(item.attr_name_id, attribute);
        })
        var attrOther = [];
        const customAttributes = Array.isArray(this.form.customAttributes) ? this.form.customAttributes : JSON.parse(this.form.customAttributes || '[]');
        customAttributes.forEach(item => {
          if (item.attr_name_id != 2) {
            if (item.attr_name_id == -1) {
              if (item.attr_name != '' && item.attr_name != undefined) {
                item.zhName = item.attr_name;
                item.attr_value_id = -1;
                item.values = undefined;
                item.attributeShowTypeValue = 'input';
                item.required = '0';
                attrOther.push(item);
              }
            } else {
              var attribute = resMap.get(item.attr_name_id);
              if (attribute == undefined) {
                attribute = {
                  'attr_name_id': -1,
                  'attr_name': item.attr_name,
                  'zhName': item.attr_name,
                  'attr_value_id': -1,
                  'attr_value': item.attr_value,
                  'values': [],
                  'attributeShowTypeValue': 'input',
                  'required': 0
                };
                resMap.set(item.attr_name_id, attribute);
              } else {
                if (item.attr_value_id != -1) {
                  // 获取是否有值
                  if (attribute.attributeShowTypeValue == 'check_box') {
                    var attr_value_id = attribute.attr_value_id;
                    if (attr_value_id == undefined) {
                      attribute.attr_value_id = [item.attr_value_id];
                    } else {
                      attribute.attr_value_id.push(item.attr_value_id);
                    }
                  } else {
                    attribute.attr_value_id = item.attr_value_id;
                    attribute.attr_value = item.attr_value;
                  }
                }
              }
            }
          }
        });
        var attr = [];
        resMap.forEach((key, val) => {
          attr.push(key);
        });
        attr.sort((a, b) => Number(b.required) - Number(a.required));
        attr = [...attr, ...attrOther];
        const newArr = []
        attr.forEach(item => {
          if ((item.attr_value && item.attr_value != -1) || (item.attr_value_id && item.attr_value_id != -1)) {
            newArr.push(item)
          }
        })
        this.$set(this.form, 'customAttributes', newArr);
      });
    },
    onHide() {
      this.visible = false;
    },
    clickStyle(index) {
      this.hoveIndex = index;
      this.showMyImg = false;
    },
    moveLeft() {
      var carLeft;
      if (this.carouselLeft - 65 * 3 <= 0) {
        carLeft = 0;
      } else {
        carLeft = this.carouselLeft - 65 * 3;
      }
      this.carouselLeft = carLeft;
    },
    moveRight() {
      var carLeft;
      if (this.carouselLeft + 65 * 3 >= this.form.imageURLs.length * 65) {
        carLeft = this.carouselLeft;
      } else {
        carLeft = this.carouselLeft + 65 * 3;
      }
      this.carouselLeft = carLeft;
    },
  },
};
</script>

<style lang="scss">
.displayBox {
  display: flex;
  flex-wrap: wrap;

  .flexbox {
    width: 50%;
    display: flex;

    .el-form-item__content {
      flex: 1;
      margin-left: 0 !important;
    }
  }

  .box-input-item-class {
    display: flex;
    // justify-content: space-between;
    align-items: center;
    margin-bottom: 20px;


    .close-span {
      padding-left: 10px;
      font-size: 14px;
      line-height: 36px;
      color: #999999;
      cursor: pointer;

      &:hover {
        color: #1890ff;
      }
    }
  }
}

.publicgoods-details-container {
  .clearfix:after {
    content: ".";
    display: block;
    height: 0;
    clear: both;
  }

  .product {
    width: 100%;
    display: flex;
    justify-content: space-between;
    padding: 20px 0;
    margin-bottom: 20px;

    .proLeft {
      width: 448px;
      min-height: 448px;
      position: relative;

      .spec {
        width: 100%;
        height: 62px;
        position: relative;
        margin-top: 12px;

        .specUl {
          height: 100%;
          position: absolute;
          top: 0;
          left: 0;
          display: flex;
          flex-direction: row;
          justify-content: space-around;
          align-items: center;

          .specImg-wrapper {
            width: 58px;
            max-height: 58px;
            border: 1px solid #EFEFEF;
            padding: 2px;
            cursor: pointer;
            text-align: center;
            background: #fff;

            .specImg {
              width: 100%;

            }

          }

          .ulImgActive {
            border: 1px solid red;
          }
        }

        .specCount {
          width: 448px;
          height: 100%;
          margin: 0 auto;
          position: relative;
          overflow: hidden;
        }

        .specLeft {
          font-size: 30px;
          color: #e2e2e2;
          position: absolute;
          left: 0px;
          top: 0;
          cursor: pointer;
          background: rgba(0, 0, 0, 0.4);
          min-height: 62px;
          z-index: 1;

          i {
            position: relative;
            right: 50%;
            top: 50%;
            transform: translateX(50%) translateY(50%);
          }
        }

        .specRight {
          font-size: 30px;
          color: #e2e2e2;
          position: absolute;
          right: 0;
          top: 0;
          cursor: pointer;
          background: rgba(0, 0, 0, 0.4);
          min-height: 62px;
          z-index: 1;

          i {
            position: relative;
            right: 50%;
            top: 50%;
            transform: translateX(50%) translateY(50%);
          }
        }
      }

      .lgImg {
        width: 448px;
        height: 448px;
        overflow: hidden;
        position: absolute;
        top: 0;
        left: 100%;
        background: #eee;
        z-index: 99;

        background-repeat: no-repeat;
        background-size: 300% 300%;
      }

      .lgImg img {
        display: none;
        width: 448px;
        height: 448px;
        overflow: hidden;
        position: absolute;
        transform: scale(3);
      }
    }

    .proCenter {
      width: calc(100% - 448px);
      padding: 5px 18px 5px 30px;
      box-sizing: border-box;

      .proCenterTop {
        width: 100%;
        font-size: 22px;
        color: #292929;
        font-weight: 400;

        span {
          padding: 0 10px;
        }
      }

      .selectBox {
        font-size: 16px;
        padding-top: 10px;

        .tagBox-item {
          display: flex;
          align-items: flex-start;
          padding-bottom: 10px;
          color: #747474;
        }

        .tagBox-item-list {
          display: flex;
          flex-wrap: wrap;
          align-items: center;

          .tag-wrapper {
            border-radius: 2px;
            border: 1px solid #E0E0E0;
            text-align: center;
            line-height: 22px;
            margin-right: 10px;
            margin-bottom: 10px;
            padding: 0 6px;
            cursor: pointer;
          }

          .activeTag {
            border: 1px solid blue;
          }
        }
      }

      .proCenterCenter {
        .proCenterCenterFirst {
          font-size: 12px;
          line-height: 40px;

          .proCenter-style {
            display: flex;
            align-items: center;

            .grossWeight {
              margin-left: 20px;
            }
          }
        }

        .product-pice {
          background-color: #FAFAFA;
          border-radius: 2px;
          line-height: 60px;
          padding: 0 15px;

          .pice {
            font-size: 16px;
            font-weight: bold;
            margin: 0 15px;
            color: #92A8D1;
          }
        }

        .product-id {
          font-size: 12px;
          padding: 0 38px;
          line-height: 50px;
          border-bottom: 1px solid #eee;
        }
      }
    }
  }

  .content-wrapper {
    .content-title-wrapper {
      width: 100%;
      box-sizing: border-box;
      line-height: 40px;
      border: 1px solid #E7E7E7;
      border-bottom-color: #FF6A00;
      background-color: #F7F7F7;
      color: #747474;

      .content-title {
        cursor: pointer;
        float: left;
        padding: 0 24px;
      }

      .active {
        background-color: #ff6a00;
        color: #fff;
      }
    }

    .content {
      padding: 5px 20px;
      padding-top: 20px;
      margin-bottom: 50px;

      .detail-content {
        font-size: 14px;
        font-weight: 300;
        line-height: 20px;
        white-space: pre-wrap;
        color: #000000;
        padding: 0 15%;
        margin: 0 auto 12px;
      }

      .detail-img {
        padding: 0 15%;
        display: flex;
        flex-direction: column;
        align-items: center;

        .ulImg {
          width: 80%;

          img {
            width: 100%;
          }
        }
      }
    }
  }

  .paramBox {
    margin: 0 auto;
    text-align: center;
  }

  .paramBoxTitle {
    font-size: 26px;
    line-height: 52px;
  }

  .bgColor {
    background: #333;
    color: #fff;
    font-size: 16px;
    line-height: 38px;
  }

  .paramLineGray {
    background: #eee;
    font-size: 16px;
    line-height: 38px;
    border-right: 1px solid #9f9f9f;
  }

  .paramLine {
    font-size: 16px;
    line-height: 38px;
    border-right: 1px solid #9f9f9f;
  }

  .shadeBox {
    width: 100%;
    height: 100%;
    background: #2b2b2b;
    opacity: 0.2;
    position: fixed;
    top: 0;
    left: 0;
  }

  .img_box {
    width: 448px;
    height: 448px;
    position: relative;
    cursor: crosshair;
    border-radius: 2px;
    border: 1px solid #eee;
    box-sizing: border-box;

    img {
      width: 100%;
      height: 100%;
      object-fit: contain;
    }

    &:hover {
      .img-yuan {
        opacity: 0.5;
      }
    }
  }

  .big_img_box {
    position: absolute;
    top: 0px;
    left: 460px;
    width: 448px;
    height: 448px;
    overflow: hidden;
    z-index: 100;
    border-radius: 2px;
    border: 1px solid rgba(0, 0, 0, 0.5);
    box-shadow: 0px 0px 15px 0px rgba(0, 0, 0, 0.5);
    background: #fff;
  }

  .mark {
    width: 260px;
    height: 260px;
    position: absolute;
    top: 0;
    left: 0;
    overflow: hidden;
    border: 1px solid #999;
    box-shadow: 0px 0px 15px 0px rgba(0, 0, 0, 0.5);
    box-sizing: border-box;
    background: #fff;

    img {
      width: 448px;
      height: 448px;
      position: absolute;
      left: 0;
      top: 0;
      opacity: 1;

      &:hover {
        cursor: crosshair;
      }
    }

    .el-image {
      width: 448px;
      height: 448px;
      position: absolute;
      left: 0;
      top: 0;
      opacity: 1;
    }
  }

  .big_img_box img {
    width: 768px;
    height: 768px;
    object-fit: contain;
    position: absolute;
    left: 0;
    top: 0;
  }

  .preview {
    width: 100%;
    border: 1px solid #eee;
    position: relative;

    &:hover {
      cursor: crosshair;
    }
  }

  .marks {
    width: 160px;
    height: 160px;
    background: rgba(0, 0, 0, 0.6);
    position: absolute;

  }

  .imgMagnify {
    font-size: 20px;
    text-align: center;
    cursor: pointer;
    position: absolute;
    bottom: 0;
    right: 0;
    background: #eee;
    color: #fff;
    padding: 5px;
  }

  .preImg {
    width: 100%;
    border: 1px solid #fff;
  }
}</style>
